import React, { Component, Fragment } from 'react';
import { Table, Input, Button, Popconfirm, Form, Icon, InputNumber } from 'antd';
//import Region from './region'
import Region from './selectAddress';
import styles from './FromTable.less';
const FormItem = Form.Item;
const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = () => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {     
      for (let key in values) {
        if (values[key] == undefined || values[key] < 0) {
          return;
        }
      }
      if (error) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  tableInputChange = (e, type, index) => {
    const { changeStatus } = this.props;
    changeStatus(e, type, index);    
  };

  limitDecimals = (value) => {
    const reg = /^(\-)*(\d+)\.(\d\d).*$/;   
    if(typeof value === 'string') {
        return !isNaN(Number(value)) ? value.replace(reg, '$1$2.$3') : ''
    } else if (typeof value === 'number') {
        return !isNaN(value) ? String(value).replace(reg, '$1$2.$3') : ''
    } else {
        return ''
    }
};

componentWillMount() {
    window.Isoption = false;
  }
  componentDidMount() {
    window.Isoption = true;
  }

  render() {
    const { editing } = this.state;
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      FirstAmountStatusList,
      FirstFeeStatusList,
      AdditionalAmountStatusList,
      AdditionalFeeStatusList,
      handleSave,
      changeStatus,
      int,
      ...restProps
    } = this.props;    
    let type =
      this.props.dataIndex == 'FirstFee'
        ? 1
        : this.props.dataIndex == 'FirstAmount'
          ? 2
          : this.props.dataIndex == 'AdditionalAmount'
            ? 4
            : this.props.dataIndex == 'AdditionalFee'
              ? 3
              : 0;
    const statusList =
      this.props.dataIndex == 'FirstFee'
        ? FirstFeeStatusList
        : this.props.dataIndex == 'FirstAmount'
          ? FirstAmountStatusList
          : this.props.dataIndex == 'AdditionalAmount'
            ? AdditionalAmountStatusList
            : this.props.dataIndex == 'AdditionalFee'
              ? AdditionalFeeStatusList
              : [];
    return (
      <td ref={node => (this.cell = node)} {...restProps} valign="middle">
        {editable ? (
          <EditableContext.Consumer>
            {form => {
              this.form = form;
              return editing ? (
                int ? (
                  <FormItem validateStatus={statusList[index]}>
                    {form.getFieldDecorator(`${dataIndex}`, {
                      // rules: [{
                      //     required: true,
                      //     message: ``,
                      // }],
                      validateTrigger: 'onBlur',
                      initialValue: record[dataIndex],
                    })(
                      // <Input
                      //     ref={node => (this.input = node)}
                      //     onPressEnter={this.save}
                      //     onBlur={this.save}

                      // />
                      <InputNumber
                        min={0}
                        max={9999999}
                        ref={node => (this.input = node)}
                        onBlur={this.save}
                        formatter={value => `${value}`.replace(/(\.)|(\D)/g, '')}
                        parser={value => value.replace(/(\.)|(\D)/g, '')}
                        onChange={e => this.tableInputChange(e, type, index)}
                        data-index={record.Id}
                      />
                    )}
                  </FormItem>
                ) : (
                  <FormItem
                    validateStatus={statusList[index]}
                  >
                    {form.getFieldDecorator(`${dataIndex}`, {
                      // rules: [{
                      //     required: true,
                      //     //message: `${title} 必须填写.`,
                      // }],
                      validateTrigger: 'onBlur',
                      initialValue: record[dataIndex],
                    })(
                      <InputNumber
                        min={0}
                        max={9999999}
                        ref={node => (this.input = node)}
                        onBlur={this.save}
                        data-index={record.Id}
                        onChange={e => this.tableInputChange(e, type, index)}
                        // formatter={value => `${value}`.replace(/\D/g, '')}
                        // parser={value => value.replace(/\D/g, '')}
                        formatter={this.limitDecimals}
                        parser={this.limitDecimals}
                      />
                    )}
                  </FormItem>
                )
              ) : (
                <div onClick={this.toggleEdit} className="Info edit-cell">
                  {restProps.children}
                </div>
              );
            }}
          </EditableContext.Consumer>
        ) : (
          restProps.children
        )}
      </td>
    );
  }
}

export default class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      selectItem: {},
      hideItems: [],
      dataSource: [],
    };
    this.FirstAmountStatusList = [];
    this.FirstFeeStatusList = [];
    this.AdditionalAmountStatusList = [];
    this.AdditionalFeeStatusList = [];
    this.columns = [
      {
        title: '指定配送区域',
        //dataIndex: 'RegionNames',
        key: 'Id',
        render: (text, data, index) => (
          <div className="Info">
            <span className="Icons">
              <Icon type="edit" onClick={() => this.EditItemRegion(index, data)} />
              <Popconfirm title="确认删除？" onConfirm={() => this.handleDelete(data.id)}>
                <Icon type="delete" />
              </Popconfirm>
            </span>
            {data && data.RegionNames ? data.RegionNames.join(',') : ''}
          </div>
        ),
      },
      {
        title: '首件(个)',
        dataIndex: 'FirstAmount',
        key: 'FirstAmount',
        editable: true,
        int: true,
      },
      {
        title: '运费(元)',
        dataIndex: 'FirstFee',
        key: 'FirstFee',
        editable: true,
        int: false,
      },
      {
        title: '续件(个)',
        dataIndex: 'AdditionalAmount',
        key: 'AdditionalAmount',
        editable: true,
        int: true,
      },
      {
        title: '续费(元)',
        dataIndex: 'AdditionalFee',
        key: 'AdditionalFee',
        editable: true,
        int: false,
      },
    ];
  }
  //初始化 dataSource
  //首次进入 state.dataSource 长度为0 则绑定 表单value值
  //再次编辑时  state.dataSource 长度不为0  直接修改state  绑定表单
  static getDerivedStateFromProps(nextProps, prveProps) {
    if (
      nextProps.value &&
      JSON.stringify(nextProps.value) !== JSON.stringify(prveProps.dataSource)
    ) {
      return {
        dataSource: [...nextProps.value],
      };
    } else {
      return null;
    }
  }
  handleDelete = Id => {
    const { dataSource } = this.state;

    this.setFromData(dataSource.filter(item => item.id !== Id));
  };

  selectRegion = () => {
    this.getAllHideItem();
  };
  EditItemRegion = (index, item) => {
    this.getAllHideItem(index, item);
  };
  handleAdd = newData => {
    const { dataSource } = this.state;
    let valueMap = dataSource;

    let id = newData.id;
    let index = valueMap.findIndex(item => item.id === id);
    if (index < 0) {
      valueMap.push(newData);
    } else {
      valueMap[index] = newData;
    }
    this.setFromData(valueMap);
  };
  disabled = dateindex => {
    const { dataSource } = this.state;
    dataSource[dateindex];
  };
  handleSave = row => {
    const newData = [...this.state.dataSource];
    const index = newData.findIndex(item => row.id === item.id);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });

    this.setFromData(newData);
  };

  changeStatus = (value, type, index) => {
    console.log(type)
    if (type == 1) {
      if (value) {
        this.FirstFeeStatusList[index] = 'success';
      } else {
        this.FirstFeeStatusList[index] = 'error';
      }
    } else if (type == 2) {
      if (value) {
        this.FirstAmountStatusList[index] = 'success';
      } else {
        this.FirstAmountStatusList[index] = 'error';
      }
    } else if (type == 3) {
      if (value) {
        this.AdditionalFeeStatusList[index] = 'success';
      } else {
        this.AdditionalFeeStatusList[index] = 'error';
      }
    } else if (type == 4) {
      if (value) {
        this.AdditionalAmountStatusList[index] = 'success';
      } else {
        this.AdditionalAmountStatusList[index] = 'error';
      }
    }
  };

  setFromData = data => {
    const { form } = this.props;
    form.setFieldsValue({
      ValuationRules: [...data],
    });
  };

  getAllHideItem = (num, item) => {
    const { dataSource } = this.state;
    let arr = [];
    if (dataSource && dataSource.length) {
      dataSource.forEach((item, index) => {
        if (item.RegionIds && item.RegionIds.length) {
          if (num > -1) {
            if (index != num) {
              arr = arr.concat(item.RegionIds);
            }
          } else {
            arr = arr.concat(item.RegionIds);
          }
        }
      });
    }
    if (num > -1) {
      this.setState({
        visible: true,
        selectItem: item,
        hideItems: arr,
      });
    } else {
      this.setState({
        hideItems: arr,
        visible: true,
        selectItem: null,
      });
    }
  };

  render() {
    const { dataSource, selectItem, hideItems } = this.state;
    // const hideItems=this.getAllHideItem();
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };

    const columns = this.columns.map((col, index) => {
      if (!col.editable) {
        return col;
      }
      let count = 0;
      this.FirstAmountStatusList[count] = 'success';
      this.FirstFeeStatusList[count] = 'success';
      this.AdditionalAmountStatusList[count] = 'success';
      this.AdditionalFeeStatusList[count] = 'success';
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          disabled: col.disabled ? true : false,
          title: col.title,
          int: col.int,
          index: ++count,
          FirstAmountStatusList: this.FirstAmountStatusList,
          FirstFeeStatusList: this.FirstFeeStatusList,
          AdditionalAmountStatusList: this.AdditionalAmountStatusList,
          AdditionalFeeStatusList: this.AdditionalFeeStatusList,
          handleSave: this.handleSave,
          changeStatus: this.changeStatus,
        }),
      };
    });
    const footer = () => <a onClick={() => this.selectRegion()}>新增可配送区域和运费</a>;
    return (
      <div className={styles.formTable}>
        <Table
          rowKey={record => record.Id || Math.random()}
          components={components}
          rowClassName={() => 'EditableRow'}
          bordered
          dataSource={dataSource}
          columns={columns}
          pagination={false}
          footer={footer}
        />
        {this.state.visible ? (
          <Region _this={this} visible={true} selectItem={selectItem} hideItems={hideItems} />
        ) : null}
      </div>
    );
  }
}
